package com.ustudy.tools.ui.Runner;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.imageio.ImageIO;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;

public class Concurrency extends Application{
	
	public static void main(String[] args) throws InterruptedException {
		launch(args);
//		CountDownLatch countDownLatch=new CountDownLatch(1);
//		ExecutorService executorService=Executors.newFixedThreadPool(10);
//		for (int i = 0; i < 10; i++) {
//			executorService.execute(new Runnable() {
//				public void run() {
//					System.out.println("starting...");
//					try {
//						countDownLatch.await();
//					} catch (InterruptedException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					};
//					System.out.println("completed...");
//				}
//			});
//			
//			
//		}
//		Thread.sleep(3000);
//		countDownLatch.countDown();
//		executorService.shutdown();
//		System.out.println("all finished...");
	}

	public void start(Stage primaryStage) throws Exception {
		primaryStage.setTitle("并发测试");
		primaryStage.setWidth(1024);
		primaryStage.setHeight(768);
		BorderPane borderPane=new BorderPane();
		borderPane.setTop(this.createTop());
		borderPane.setCenter(this.createCenter());
		primaryStage.setScene(new Scene(borderPane));
		primaryStage.show();
	}
	
	public Node createTop() {
		HBox top=new HBox();
		top.setPadding(new Insets(20));
		top.setSpacing(10);
		TextField url=new TextField();
		url.setPromptText("请输入请求地址...");
		url.setPrefWidth(450);
		top.getChildren().add(url);
		TextField number=new TextField();
		number.setPromptText("线程");
		number.setText("100");
		number.setPrefWidth(80);
		top.getChildren().add(number);
		ComboBox<String> method=new ComboBox<>();
		method.getItems().addAll("get","post");
		method.setValue("get");
		top.getChildren().add(method);
		Button request=new Button("发送请求");
		request.addEventHandler(MouseEvent.MOUSE_CLICKED,new EventHandler<MouseEvent>() {
			public void handle(MouseEvent event) {
				while(!center.getChildren().isEmpty()) {
					center.getChildren().remove(0);
				}
				CountDownLatch countDownLatch=new CountDownLatch(1);
				
				int threadCount=Integer.parseInt(number.getText());
				CountDownLatch countDownLatch2=new CountDownLatch(threadCount);
				final String u=url.getText();
				ExecutorService executorService=Executors.newFixedThreadPool(threadCount);
				for (int i = 0; i < threadCount; i++) {
					Button b=createThreadFlags();
					center.getChildren().add(b);
					executorService.execute(new Runnable() {
						public void run() {
							try{
								HttpURLConnection connection=(HttpURLConnection) new URL(u).openConnection();
								
								Platform.runLater(new Runnable() {
									public void run() {
										b.setGraphic(new ImageView(new Image(new ByteArrayInputStream(blue))));
									}
								});
								//TODO await
								countDownLatch2.countDown();
								countDownLatch.await();
								connection.connect();
								try(BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));){
									StringBuilder res=new StringBuilder();
									String buff=br.readLine();
									while(buff!=null) {
										res.append(buff);
										buff=br.readLine();
									}
									b.setUserData(res);
									Platform.runLater(new Runnable() {
										public void run() {
											b.setGraphic(new ImageView(new Image(new ByteArrayInputStream(green))));
										}
									});
								}catch(Exception e) {
									Platform.runLater(new Runnable() {
										public void run() {
											b.setGraphic(new ImageView(new Image(new ByteArrayInputStream(red))));
										}
									});
								}
								connection.disconnect();
							}catch(Exception e) {
								Platform.runLater(new Runnable() {
									public void run() {
										b.setGraphic(new ImageView(new Image(new ByteArrayInputStream(red))));
									}
								});
							}
							
							
						}
					});
				}
				
				new Thread(new Runnable() {
					public void run() {
						try {
							countDownLatch2.await();
							countDownLatch.countDown();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}).start();
				
				executorService.shutdown();
			}
		});
		top.getChildren().add(request);
		return top;
	}
	
	private FlowPane center;
	
	public Node createCenter() throws IOException {
		FlowPane flowPane=new FlowPane();
		flowPane.setVgap(0);
		flowPane.setHgap(0);
		this.center=flowPane;
		return flowPane;
	}
	
	
	protected Button createThreadFlags(){
		Button b=new Button("",new ImageView(new Image(new ByteArrayInputStream(defcolor))));
		b.setPrefSize(20, 20);
		b.setPadding(new Insets(1));
		b.setBorder(null);
		b.setUserData("初始化...");
		b.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
			public void handle(MouseEvent arg0) {
				Alert alert=new Alert(AlertType.INFORMATION);
				alert.setTitle("提示");
				alert.setHeaderText("状态");
				alert.setContentText("");
				alert.setWidth(1024);
				alert.setHeight(800);
				TextArea textArea=new TextArea(b.getUserData().toString());
				textArea.setEditable(false);
				textArea.setWrapText(true);
				GridPane.setVgrow(textArea, Priority.ALWAYS);
				GridPane.setHgrow(textArea, Priority.ALWAYS);
				GridPane expContent = new GridPane();
				expContent.setMaxWidth(Double.MAX_VALUE);
				expContent.add(textArea, 0, 1);
				alert.getDialogPane().setExpandableContent(expContent);
				alert.showAndWait();
			}
			
		});
		return b;
	}
	
	private byte[] defcolor;
	{
		BufferedImage img=new BufferedImage(20, 20,BufferedImage.TYPE_INT_BGR);
		Graphics2D g2d=(Graphics2D) img.getGraphics();
		g2d.setColor(new Color(0xffaaaaaa));
		g2d.fillRect(0, 0, 20, 20);
		ByteArrayOutputStream out=new ByteArrayOutputStream();
		try {
			ImageIO.write(img,"png",out);
			defcolor=out.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private byte[] red;
	{
		BufferedImage img=new BufferedImage(20, 20,BufferedImage.TYPE_INT_BGR);
		Graphics2D g2d=(Graphics2D) img.getGraphics();
		g2d.setColor(new Color(0xffff0000));
		g2d.fillRect(0, 0, 20, 20);
		ByteArrayOutputStream out=new ByteArrayOutputStream();
		try {
			ImageIO.write(img,"png",out);
			red=out.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private byte[] blue;
	{
		BufferedImage img=new BufferedImage(20, 20,BufferedImage.TYPE_INT_BGR);
		Graphics2D g2d=(Graphics2D) img.getGraphics();
		g2d.setColor(new Color(0xff0000ff));
		g2d.fillRect(0, 0, 20, 20);
		ByteArrayOutputStream out=new ByteArrayOutputStream();
		try {
			ImageIO.write(img,"png",out);
			blue=out.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private byte[] green;
	{
		BufferedImage img=new BufferedImage(20, 20,BufferedImage.TYPE_INT_BGR);
		Graphics2D g2d=(Graphics2D) img.getGraphics();
		g2d.setColor(new Color(0xff00ff00));
		g2d.fillRect(0, 0, 20, 20);
		ByteArrayOutputStream out=new ByteArrayOutputStream();
		try {
			ImageIO.write(img,"png",out);
			green=out.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static class Datas{
		
		private String url;
		
		private String status;
		
		private Map<String,String> reqHeaders;
		
		private Map<String,String> resHeaders;
		
		private Map<String,String> params;
		
		private String content;

		public String getUrl() {
			return url;
		}

		public void setUrl(String url) {
			this.url = url;
		}

		public String getStatus() {
			return status;
		}

		public void setStatus(String status) {
			this.status = status;
		}

		public Map<String, String> getReqHeaders() {
			return reqHeaders;
		}

		public void setReqHeaders(Map<String, String> reqHeaders) {
			this.reqHeaders = reqHeaders;
		}

		public Map<String, String> getResHeaders() {
			return resHeaders;
		}

		public void setResHeaders(Map<String, String> resHeaders) {
			this.resHeaders = resHeaders;
		}

		public Map<String, String> getParams() {
			return params;
		}

		public void setParams(Map<String, String> params) {
			this.params = params;
		}

		public String getContent() {
			return content;
		}

		public void setContent(String content) {
			this.content = content;
		}
	}
}
